package com.xiangxiangjd.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.xiangxiangjd.config.token.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @author jinbin
 * @date 2018-07-08 20:41
 */
public class AuthenticationInterceptor implements HandlerInterceptor {



    @Autowired
    private JwtUtils jwtUtils;


    @Override
    public boolean preHandle(HttpServletRequest request1, HttpServletResponse response, Object object) throws Exception {


        System.out.println("请求方法:"+request1.getMethod());

        String token = request1.getHeader("token");

        System.out.println("本次访问的路径"+request1.getRequestURI());


        //解析token
        Claims claims = jwtUtils.parseJwt(token);

        //获取id 是不是-1
        Integer id = Integer.valueOf(claims.getId());
        //是-1 为用户回答





        System.out.println("token 是否存在:"+token);
        if (token == null) {
            System.out.println("token不存在");

            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            JSONObject res = new JSONObject();
            res.put("success", "false");
            res.put("code", "501");
            res.put("msg", "token 不存在!");
            response.getWriter().append(res.toString());
            return false;
        }


        if (claims==null){
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            JSONObject res = new JSONObject();
            res.put("success", "false");
            res.put("code", "502");
            res.put("msg", "登录过期 请重新登录!");
            response.getWriter().append(res.toString());
            return false;
        }




        System.out.println("验证token 成功"+claims);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
